<?php
/***************************************************************
*  Copyright notice
*  (c) 2009, jianyuzhu@gmail.com
*  All rights reserved
*  This script is part of the PPEMI project.
***************************************************************/

//
$setting_gzip = 1;

//Initialise GZIP
function func_gzip_init() {
	global $setting_gzip, $do_gzip_compress;
	$do_gzip_compress = false;
	
	//zlib.output_compression and ob_gzhandler don't get along well so we'll check to make
	//that zlib.output_compression is not enable in the php.ini before turning on ob_gzhandler
	if( $setting_gzip == 1 && (int)ini_get('zlib.output_compression') != 1 ) {
		$pv = phpversion();
		$ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
		$ae = isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : '';
		
		if( $pv >= '4.0.4pl1' && ((strpos($ua, 'compatible') !== false) || (strpos($ua, 'Gecko') !== false)) ) {
			if( extension_loaded('zlib') ) {
				ob_start('ob_gzhandler');
				return;
			}
		} elseif( $pv > '4.0' ) {
			if( strpos($ae, 'gzip') !== false ) {
				if( extension_loaded('zlib') ) {
					$do_gzip_compress = true;
					ob_start();
					ob_implicit_flush(0);
					
					header('Content-Encoding: gzip');
					return;
				}
			}
		}
	}
}

//Perform GZIP
function func_gzip_perform() {
	global $do_gzip_compress;
	
	if( $do_gzip_compress == true ) {
		$gzip_contents = ob_get_contents();
		ob_end_clean();
		
		$gzip_size = strlen($gzip_contents);
		$gzip_crc = crc32($gzip_contents);

		$gzip_contents = gzcompress($gzip_contents, 9);
		$gzip_contents = substr($gzip_contents, 0, strlen($gzip_contents) - 4);

		echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";
		echo $gzip_contents;
		echo pack('V', $gzip_crc);
		echo pack('V', $gzip_size);
	} else {
		ob_end_flush();
	}
}
//
?>